import { Component, OnInit, Inject, forwardRef, ChangeDetectorRef, ViewChild } from '@angular/core';
import { FileUploader } from '../../../../../lib/ng2-file-upload';
import { TabsetComponent } from 'ngx-bootstrap';
import { AppComponent } from '../../../../app.component';

import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service'
import { path } from '../../../../path.config';
import { NzModalService } from 'ng-zorro-antd';

@Component({
    selector: 'h5-lead-download-activity-edit',
    templateUrl: './lead-download-activity-edit.component.html',
    styleUrls: ['./lead-download-activity-edit.component.css']
})
export class LeadDownloadActivityEditComponent implements OnInit {
    @ViewChild('leadDownloadActivityEdit') private leadDownloadActivityEdit: TabsetComponent;

    // api
    // 上传图片
    private addImgItem = path.imagesUpload.apiUrl;
    // 获取图片id
    private getImgId = path.imagesUpload.getImgId;
    // 活动查询商品列表
    private searchList = path.campaignManage.oneClickActivity.searchList;
    // 更新基础信息
    private updateBasicInfo = path.campaignManage.oneClickActivity.updateBasicInfo;
    // 更新活动商品
    private updateGoodsDetail = path.campaignManage.oneClickActivity.updateGoodsDetail;


    // 单、多品活动radio默认值
    IsActivitySingle = false;
    IsActivityMultiple = false;

    // 选择活动商品搜索的列表(单品，多品)
    goodsSearchList1 = [];
    goodsSearchList2 = [];
    // 单品活动 已选择的商品
    singleActivity = '';
    singleActivityGoodsId;
    // 多品活动输入框绑定的值(没什么用)
    multipleActivitySearch = '';
    // 多品活动 已选择的商品
    multipleActivity = [];
    // 基础信息提交返回,每次post请求需要
    activityId = '';
    // 记录当前的tab下标
    LeadDownloadType = 1;

    // 上传图片 分享缩略图
    shareImageUpload: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 多品活动 图片
    headImageIdUpload: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    uploadPic = {};

    // 已选活动商品列表
    multipleActivityColumns = [
        { 'title': '排序', name: '' },
        { 'title': '已选活动商品', name: '' },
        { 'title': '操作', name: '' }
    ]

    // 基础信息请求数据
    public basicInfoModel = {
        "activityId": "",
        "activityName": "",
        "shareImageId": "",
        "shareImageIdUrl": "",
        "shareTitle": "",
        "shareDesicription": ""
    }

    // 活动详情请求数据
    public goodsDetailModel = {
        "activityId": "",
        "activityType": "1",
        "headImageId": "",
        "headImageIdUrl": "",
        "goodsList": []
    }

    editModel: any;
    constructor(private _masterService: masterService,
        private _saveVar: saveVarService,
        private cdRef: ChangeDetectorRef,
        private confirmServ: NzModalService,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() {
        // 编辑值
        this.editModel = this._saveVar.leadDownloadEdit;
        this._masterService
            .openLeadDownload
            .subscribe((res) => {
                if (res) {
                    this.editModel = res;
                    this.initEdit();
                }
            })
        this.initEdit();
    }


    ngOnDestroy() {
        this.cdRef.detach();
    }

    // 选择tab时改变LeadDownloadType
    selectType(type) {
        this.LeadDownloadType = type;
    }

    // 绑定编辑值
    initEdit() {
        // 基础信息请求数据
        this.basicInfoModel = {
            "activityId": this.editModel.basicInfo.activityId,
            "activityName": this.editModel.basicInfo.activityName,
            "shareImageId": this.editModel.basicInfo.shareImageId,
            "shareImageIdUrl": this.editModel.basicInfo.sharePicUrl,
            "shareTitle": this.editModel.basicInfo.shareTitle,
            "shareDesicription": this.editModel.basicInfo.shareDesicription
        }

        // 活动详情请求数据
        this.goodsDetailModel = {
            "activityId": this.editModel.basicInfo.activityId,
            "activityType": '' + this.editModel.basicInfo.activityType,
            "headImageId": this.editModel.basicInfo.headImageId,
            "headImageIdUrl": this.editModel.basicInfo.pageHeadPicUrl,
            "goodsList": this.editModel.activityGoodsList
        }
        if (this.editModel.basicInfo.activityType == '1' && this.editModel.activityGoodsList.length > 0) {
            this.singleActivity = 'id=' + this.editModel.activityGoodsList[0].goodsId + '  ' + this.editModel.activityGoodsList[0].goodsName;
        }

        this.multipleActivity = this.goodsDetailModel.goodsList;
    }

    // 上传图片
    uploadFile(uploader?, uploadType?) {
        let thisItem = (uploader.length == 1) ? uploader.queue[0] : uploader.queue[uploader.queue.length - 1];
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning("请选择图片");
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: thisItem.some.name,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            if (uploadType == 'shareImageUpload') {
                                that.basicInfoModel.shareImageId = res.data;
                                that.basicInfoModel.shareImageIdUrl = tempRes.data.url[0];
                            } else if (uploadType == 'headImageIdUpload') {
                                that.goodsDetailModel.headImageId = res.data;
                                that.goodsDetailModel.headImageIdUrl = tempRes.data.url[0];
                            }
                            that.app.toastSuccess('上传成功！');
                            that.cdRef.detectChanges();
                        } else {
                            that.app.toastError('错误信息：' + res.errorMessage)
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息：' + response.errorMessage);
            }
        };

        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息：' + response.errorMessage)
        };

        thisItem.upload(); // 开始上传
    }

    selectedFileOnChanged(event: any, uploader) {
        let $this = this;
        let thisItem = uploader.queue[0] = uploader.queue[uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
        this.cdRef.detectChanges();
    }

    // 活动详情 搜索商品
    searchListFunc(goodsName, type?) {
        let urlObj = {
            goodsName: goodsName
        }
        this._masterService
            .getData(this.searchList, urlObj)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    if (type == 1) {
                        this.goodsSearchList1 = res.data;
                    } else if (type == 2) {
                        this.goodsSearchList2 = res.data;
                        // 判断是否商品是否已被选择
                        this.goodsSearchList2.forEach((goodsSearchVal, i) => {
                            this.multipleActivity.forEach((multipleActivityVal, j) => {
                                if (multipleActivityVal.goodsId == goodsSearchVal.goodsId) {
                                    goodsSearchVal.active = true;
                                }
                            })
                        })
                    }
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息：' + res.errorMessage);
                }
            })
    }

    // 活动详情 已选中的商品
    addListFunc(goodsName, type?, goodsId?) {
        if (type == 1) {
            this.singleActivity = 'id=' + goodsId + '  ' + goodsName;
            this.singleActivityGoodsId = goodsId;
        } else if (type == 2) {
            this.multipleActivity.push({
                sort: '',
                goodsId: goodsId,
                goodsName: goodsName,
                active: true
            })
        }
        this.cdRef.detectChanges();
    }

    // 删除已选择的活动商品
    deleteListItem(goodsId) {
        this.confirmServ.confirm({
            nzTitle: '是否确认删除？',
            nzOnOk() {
                postDeleteListItem();
            }
        })

        let postDeleteListItem = () => {
            let index;
            this.multipleActivity.forEach((val, i) => {
                if (val.goodsId == goodsId) {
                    index = i;
                }
            })
            this.multipleActivity.splice(index, 1);
            this.cdRef.detectChanges();
        }
    }

    // focus事件时 打开下拉列表并刷新选择状态
    mutliSearch(val) {
        this.IsActivityMultiple = true;
        this.searchListFunc(val, 2);
    }

    // 保存
    saveLeadDownload() {
        if (this.LeadDownloadType == 1) {
            this.saveBasicInfo();
        } else if (this.LeadDownloadType == 4) {
            this.saveGoodsDetail();
        }
    }

    // 基础信息保存
    saveBasicInfo() {
        if (!this.basicInfoModel.activityName) {
            this.app.toastWarning('请输入活动名称!');
            return;
        } else if (!this.basicInfoModel.shareTitle) {
            this.app.toastWarning('请输入分享标题!');
            return;
        } else if (!this.basicInfoModel.shareDesicription) {
            this.app.toastWarning('请输入分享描述!');
            return;
        } else if (!this.basicInfoModel.shareImageId) {
            this.app.toastWarning('请上传图片!');
            return;
        }

        this._masterService
            .postData(this.updateBasicInfo, this.basicInfoModel)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.app.toastSuccess('保存基础信息成功!');
                    this.activityId = res.data.id;
                    this._masterService.LeadDownloadReload.emit();
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息:' + res.errorMessage);
                }
            })
    }
    // 活动详情保存
    saveGoodsDetail() {
        // 活动类型验证
        if (!this.goodsDetailModel.activityType) {
            this.app.toastWarning('请选择活动类型!');
            return;
        }
        // 单品活动验证
        if (this.goodsDetailModel.activityType == '1') {
            if (!this.singleActivityGoodsId) {
                this.app.toastWarning('请选择单品活动商品！');
                return;
            }
            this.goodsDetailModel.goodsList = [];
            this.goodsDetailModel.headImageId = '';
            this.goodsDetailModel.headImageIdUrl = '';
            this.goodsDetailModel.goodsList.push({
                goodsId: this.singleActivityGoodsId,
                sort: '1'
            })
            // 多品活动验证
        } else if (this.goodsDetailModel.activityType == '2') {
            if (!this.goodsDetailModel.headImageId) {
                this.app.toastWarning('请上传页面头图！');
                return;
            }
            this.goodsDetailModel.goodsList = [];
            if (this.multipleActivity.length == 0) {
                this.app.toastWarning('请选择多品活动商品！');
                return;
            } else if (this.multipleActivity.length > 0) {
                for (let i = 0; i < this.multipleActivity.length; i++) {
                    if (!this.multipleActivity[i].sort) {
                        this.app.toastWarning('请输入排序顺序!');
                        return;
                    }
                    for (let j = i + 1; j < this.multipleActivity.length; j++) {
                        if (this.multipleActivity[i].sort == this.multipleActivity[j].sort) {
                            this.app.toastWarning('排序请勿重复!');
                            return;
                        }
                    }
                    this.goodsDetailModel.goodsList.push({
                        goodsId: this.multipleActivity[i].goodsId,
                        sort: this.multipleActivity[i].sort
                    })
                }
            }
        }

        this._masterService
            .postData(this.updateGoodsDetail, this.goodsDetailModel)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.app.toastSuccess('保存活动详情成功!');
                    this._masterService.LeadDownloadReload.emit();
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError("错误提示: " + res.errorMessage);
                }
            })
    }
}
